//
//  photos.m
//  SXH-Bridge
//
//  Created by sxh on 2020/9/10.
//  Copyright © 2020 yuxin. All rights reserved.
//

#import "photos.h"
#import "JSBUtil.h"
#import "PhotoSelector.h"
#import "SDWebImage.h"

@implementation photos

- (void)photos:(NSString *)type :(JSCallBack)completeHandle {
    __block NSMutableDictionary *resultDict = @{}.mutableCopy;
    if ([type isEqualToString:@"camera"]) {
        [[PhotoSelector shareInstance] openCamera:^(id  _Nullable result, NSMutableArray *errors) {
            NSArray *images = (NSArray *)result;
            NSMutableArray *tempArr = @[].mutableCopy;
            for (int i = 0; i < images.count; i++) {
                [tempArr addObject:[self imageToBase64:images[i]]];
            }
            resultDict = @{
                @"err":@(0),
                @"message":tempArr
            }.mutableCopy;
            completeHandle([JSBUtil objToJsonString:resultDict],YES);
        }];
    }else if ([type isEqualToString:@"photo"]) {
        [[PhotoSelector shareInstance] openPhotos:^(id  _Nullable result, NSMutableArray *errors) {
            NSArray *images = (NSArray *)result;
            NSMutableArray *tempArr = @[].mutableCopy;
            for (int i = 0; i < images.count; i++) {
                [tempArr addObject:[self imageToBase64:images[i]]];
            }
            resultDict = @{
                @"err":@(0),
                @"message":tempArr
            }.mutableCopy;
            completeHandle([JSBUtil objToJsonString:resultDict],YES);
        }];
    }else {
        resultDict = @{
            @"err":@(-1),
            @"message":@"传入类型错误,camera相机,photo相册"
        }.mutableCopy;
        completeHandle([JSBUtil objToJsonString:resultDict],YES);
    }
}

///options obj = {type:'相机或者相册',maxSelectCount:'可选择相片数量最高9张',saveNewImageAfterEdit:'编辑图片后是否保存'}
- (void)photoswithOptions:(id)obj :(JSCallBack)completeHandle {
    NSString *type = ((NSDictionary *)obj)[@"type"];
    NSString *maxSelectCount = ((NSDictionary *)obj)[@"maxSelectCount"];
    NSString *saveNewImageAfterEdit = ((NSDictionary *)obj)[@"saveNewImageAfterEdit"];
    if (type == nil) {
        NSAssert(type, @"传入类型不能为空");
    }
    if (maxSelectCount == nil ||
        [maxSelectCount intValue] > 9 ||
        [maxSelectCount intValue] < 1) {
        maxSelectCount = @"9";
    }
    [PhotoSelector shareInstance].maxSelectCount = [maxSelectCount intValue];
    [PhotoSelector shareInstance].saveNewImageAfterEdit = [saveNewImageAfterEdit boolValue];
    [self photos:type :completeHandle];
}

- (NSString *)imageToBase64:(UIImage *)image {
    // 压缩一下图片再传
    NSData *imgData = [self compressImageQuality:image toByte:1024*100];
//    NSString *encodeImageStr = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
    NSString *encodeImageStr = [imgData base64EncodedStringWithOptions:NSDataBase64EncodingEndLineWithCarriageReturn];
    SDImageFormat type = [NSData sd_imageFormatForImageData:imgData];
//    static const SDImageFormat SDImageFormatUndefined = -1;
//    static const SDImageFormat SDImageFormatJPEG      = 0;
//    static const SDImageFormat SDImageFormatPNG       = 1;
//    static const SDImageFormat SDImageFormatGIF       = 2;
//    static const SDImageFormat SDImageFormatTIFF      = 3;
//    static const SDImageFormat SDImageFormatWebP      = 4;
//    static const SDImageFormat SDImageFormatHEIC      = 5;
//    static const SDImageFormat SDImageFormatHEIF      = 6;
//    static const SDImageFormat SDImageFormatPDF       = 7;
//    static const SDImageFormat SDImageFormatSVG       = 8;
    NSString *imageType = @"";
    switch (type) {
        case SDImageFormatPNG:
            imageType = @"png";
            break;
        case SDImageFormatJPEG:
            imageType = @"jpeg";
            break;
        case SDImageFormatGIF:
            imageType = @"gif";
            break;
        case SDImageFormatSVG:
            imageType = @"svg";
            break;
        default:
            break;
    }
    NSLog(@"当前图片类型为：%ld -- %@", (long)type, imageType);
    NSString *imageString = [NSString stringWithFormat:@"data:image/%@;base64,%@",imageType,encodeImageStr];
    
    imageString = [imageString stringByReplacingOccurrencesOfString:@" " withString:@""];
    imageString = [imageString stringByReplacingOccurrencesOfString:@"\r" withString:@""];
    imageString = [imageString stringByReplacingOccurrencesOfString:@"\n" withString:@""];
    
    return imageString;
}

- (NSData *)compressImageQuality:(UIImage *)image toByte:(NSInteger)maxLength {
    CGFloat compression = 1;
    NSData *data = UIImageJPEGRepresentation(image, compression);
    if (data.length < maxLength) return data;
    CGFloat max = 1;
    CGFloat min = 0;
    for (int i = 0; i < 6; ++i) {
        compression = (max + min) / 2;
        data = UIImageJPEGRepresentation(image, compression);
        if (data.length < maxLength * 0.9) {
            min = compression;
        } else if (data.length > maxLength) {
            max = compression;
        } else {
            break;
        }
    }
//    UIImage *resultImage = [UIImage imageWithData:data];
//    return resultImage;
    return data;
}

@end
